#! /bin/sh

csid=$1

if [ "$#" -ne 1 ]; then
 echo "This script needs 3 input parameter"
 echo "usage: OracleAppTeardown.sh <New database sid name> <Oracle Home path> <Oracle User>"
 echo " For example: OracleAppTeardown.sh clonedb /home/oracle/app/oracle/product/11.2.0/dbhome_1 oracle"
 exit 1
fi

source /opt/howlink/lb-agent/scripts/oracle/oracleclone/OracleAppMountComFunc.sh

orahome=`cat /opt/howlink/lb-agent/application.properties | grep "^agent.oracle-home" | awk -F'=' '{ print $2 }' | sed 's/ //g'`
if [ -z "$orahome" ];then
    orahome=`grep -wi "$sid:"  $otab | grep "^$sid" | head -n1 | cut -f2 -d":"`
fi

orauser=`cat /opt/howlink/lb-agent/application.properties | grep "^agent.oracle-user" | awk -F'=' '{ print $2 }' | sed 's/ //g'`
if [ -z "$orauser" ];then
    orauser=`ps -ef | grep ora_pmon | grep -v grep | head -n1 | sed -e 's/^[ \t]*//' | cut -d" " -f1`
fi
if [ -z "$orauser" ];then
    orauser=oracle
fi

oraBase=`cat /opt/howlink/lb-agent/application.properties | grep "^agent.oracle-base" | awk -F'=' '{ print $2 }' | sed 's/ //g'`
if [ -z "$oraBase" ];then
    oraBase=/u01/app
fi

export ORACLE_HOME=$orahome
export ORACLE_SID=$csid
export ORACLE_BASE=$oraBase
export PATH=$ORACLE_HOME/bin:$PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib
export LD_LIBRARY_PATH

if [ -z $csid ]; then
   echo "need SID to proceed"
   exit 1
fi

if [ ! -d $ORACLE_HOME ]; then
   echo "could not find ORACLE_HOME "
   exit 1
fi

CSID=`echo $csid | tr [a-z] [A-Z]`
echo $CSID

function cleanup
{
   path=$1
   if [ -e $path ]; then
      echo "removing $path and all its contents"
      find $path -delete
   fi
}

nsid=`ps -ef | grep pmon | grep -i $csid | awk '{ print $NF }' | cut -f3 -d"_"`
if [ ! -z $nsid ] && [ "$nsid" = "$csid" ]; then
su -m $orauser -c "$ORACLE_HOME/bin/sqlplus -s / as sysdba << EOF
set heading off
set feedback off
shutdown immediate;
exit;
EOF
"

if [ $? != 0 ]; then
      # shutdown failed, exit without cleanup ora files
      echo "shutdown failed for $csid"
      exit 1
   fi
fi

if [ -z "$isrestore" ] || [ "$isrestore" != "true" ]; then
#removing database cluster entries
#su -m $orauser -c "$ORACLE_HOME/bin/srvctl remove database -d $csid -f &> /dev/null"

if [ "$notnsupdate" != "true" ]; then
# cleanup tns entry
/opt/howlink/lb-agent/scripts/oracle/oracleclone/cleanupTNSNames.sh $csid $ORACLE_HOME 6 $tnsadmindir
fi

setdbf=/opt/howlink/lb-agent/scripts/oracle/oracleclone/setdb_$csid

rm -f $ORACLE_HOME/dbs/init$csid.ora
rm -f $ORACLE_HOME/dbs/init$CSID.ora
rm -f $ORACLE_HOME/dbs/spfile$csid.ora
rm -f $ORACLE_HOME/dbs/spfile$CSID.ora
rm -f $ORACLE_HOME/dbs/orapw$csid
rm -f $ORACLE_HOME/dbs/orapw$CSID
rm -rf $ORACLE_BASE/admin/*$csid*
rm -rf /u01/arch
rm -fr /data/oradata
rm $setdbf
fi

echo "done rewind"
exit 0
